package cn.zjutleo.village_server.config;

import cn.hutool.core.collection.CollUtil;
import lombok.Data;
import org.apache.http.HttpHost;
import org.apache.http.util.Asserts;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;

import java.util.List;

/**
 * @author : Qin Zhenghan
 * @date : Created in 2021/8/19
 * @description: Elasticsearch配置类
 */
/**
 * @author : Qin Zhenghan
 * @date : Created in 2021/8/19
 * @description: Elasticsearch配置类
 */
@ConfigurationProperties("spring.elasticsearch.rest")
@Configuration
@Data
public class ElasticSearchConfig {

    private List<String> ipAddresses;

    private String scheme;

    /**
     * 创建 HighLevelRestClient 客户端
     *
     * @return RestHighLevelClient
     */
    @Bean
    public RestHighLevelClient restHighLevelClient() {
        return new RestHighLevelClient(RestClient.builder(buildHttpHost()));
    }

    /**
     * 创建 ElasticsearchRestTemplate(匹配高级REST客户端)
     *
     * @return ElasticsearchRestTemplate
     */
    @Bean
    public ElasticsearchRestTemplate elasticsearchRestTemplate() {
        return new ElasticsearchRestTemplate(restHighLevelClient());
    }

    private HttpHost[] buildHttpHost() {
        Asserts.check(!CollUtil.isEmpty(ipAddresses), "ES集群IP地址不可为空");
        HttpHost[] httpHosts = new HttpHost[ipAddresses.size()];
        for (int index = 0; index < ipAddresses.size(); index++) {
            String ipAddress = ipAddresses.get(index);
            String[] splits = ipAddress.split(":");
            String ip = splits[0];
            int port = Integer.parseInt(splits[1]);
            httpHosts[index] = new HttpHost(ip, port, scheme);
        }
        return httpHosts;
    }

}
